package com.example.cloud.service.business.reservation.impl;

import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.business.reservation.PatientRepository;
import com.example.cloud.model.business.reservation.Patient;
import com.example.cloud.model.statistics.CreditItems;
import com.example.cloud.model.system.User;
import com.example.cloud.service.basic.info.MemberLevelService;
import com.example.cloud.service.basic.info.MemberService;
import com.example.cloud.service.business.reservation.PatientService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by wangtao on 2018/5/17.
 */
@Service
public class PatientServiceImpl implements PatientService {

    @PersistenceContext
    EntityManager em;

    @Autowired
    private PatientRepository patientRepository;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public Patient findOne(Long id) {
        return patientRepository.findOne(id);
    }

    @Override
    public Patient findByMedicalNumber(String medicalNumber) {
        return patientRepository.findByMedicalNumberAndDeleteFlag(medicalNumber,0);
    }

    @Override
    public List<Patient> findByIds(List<Long> ids) {
        return patientRepository.findByIdIn(ids);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doSave(Patient record) {
        if(record.getId() == null){
            User u = RequestUtil.getLoginUser();
            record.setUserId(u.getId());
            record.setAccountId(u.getAccountId());
            record.setOrganId(u.getOrganId());
            record.setOrganName(u.getOrganName());
            BusinessUtil.appendRecord(record);
            patientRepository.save(record);
            // 自动开户
            memberService.openAccount(record);
        }else{
            BusinessUtil.appendRecord(record);
            patientRepository.save(record);
            // 更新预约记录的患者姓名和病历号
            StringBuilder sql = new StringBuilder("update business_reservation set patient_name = :patientName,medical_number = :medicalNumber where patient_id = :id");
            Query nativeQuery = em.createNativeQuery(sql.toString());
            nativeQuery.setParameter("patientName", record.getName());
            nativeQuery.setParameter("medicalNumber", record.getMedicalNumber());
            nativeQuery.setParameter("id", record.getId());
            nativeQuery.executeUpdate();
            // 更新会员的姓名、病历号、手机号码
            sql = new StringBuilder("update member set patient_name = :patientName,member_name = :patientName,member_number = :memberNumber,phone = :phone where patient_id = :id");
            nativeQuery = em.createNativeQuery(sql.toString());
            nativeQuery.setParameter("patientName", record.getName());
            nativeQuery.setParameter("memberNumber", record.getMedicalNumber());
            nativeQuery.setParameter("phone", record.getPhone());
            nativeQuery.setParameter("id", record.getId());
            nativeQuery.executeUpdate();
        }
    }

    @Override
    @Transactional
    public void doDelete(List<Long> ids) {
        StringBuilder sql = new StringBuilder("update basic_patient set delete_flag = 1 where id in(:ids)");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("ids", ids);
        query.executeUpdate();
    }

    @Override
    @Transactional
    public void doSetHealthCare(Patient patient) {
        StringBuilder sql = new StringBuilder("update basic_patient set");
        //更新主管医生
        sql.append(" doctor_id = :doctorId");
        sql.append(",doctor_name = :doctorName");
        // 更新主管护士
        sql.append(",nurse_id = :nurseId");
        sql.append(",nurse_name = :nurseName");
        // 更新条件为主键
        sql.append(" where id = :id");
        Query query = em.createNativeQuery(sql.toString());
        query.setParameter("doctorId", patient.getDoctorId());
        query.setParameter("doctorName", patient.getDoctorName());
        query.setParameter("nurseId", patient.getNurseId());
        query.setParameter("nurseName", patient.getNurseName());
        query.setParameter("id", patient.getId());
        query.executeUpdate();
    }

    @Override
    public boolean doCheckPhone(String phone) {
        int count = patientRepository.countByPhoneAndDeleteFlag(phone, 0);
        return count > 0;
    }

    @Override
    @Transactional
    public void doConfirm(Patient patient) {
        String medicalNumber = "";
        // 判断是否生成病历号，病历号生成规则：出生日期-信息确认日期-序号
        if(patient.getBirthday() != null){
            // 出生日期
            String key1 = new SimpleDateFormat("yyMMdd", Locale.CHINESE).format(patient.getBirthday());
            // 信息确认日期
            String key2 = new SimpleDateFormat("yyMMdd", Locale.CHINESE).format(new Date());
            String key = key1 + "-" + key2;
            // 检索患者病历号是否已存在
            String sql = "select * from basic_patient where medical_number like '" + key + "%'";
            Query nativeQuery = em.createNativeQuery(sql);
            List result = nativeQuery.getResultList();
            // 序号
            String key3 = "0" + (result.size() + 1);
            medicalNumber = key + "-" + key3;
            patient.setMedicalNumber(medicalNumber);
        }
        BusinessUtil.appendRecord(patient);
        patientRepository.save(patient);

        // 判断是否开户，如果开户同步会员
        StringBuilder sql = null;
        if(patient.getIsMember() == StateConstants.IS_MEMBER_YES){
            sql = new StringBuilder("update member set patient_name = :patientName,member_number = :medicalNumber where patient_id = :id");
            Query nativeQuery = em.createNativeQuery(sql.toString());
            nativeQuery.setParameter("patientName", patient.getName());
            nativeQuery.setParameter("medicalNumber", medicalNumber);
            nativeQuery.setParameter("id", patient.getId());
            nativeQuery.executeUpdate();
        }
        // 同步所有预约数据
        sql = new StringBuilder("update business_reservation set patient_name = :patientName,medical_number = :medicalNumber where patient_id = :id");
        Query nativeQuery = em.createNativeQuery(sql.toString());
        nativeQuery.setParameter("patientName", patient.getName());
        nativeQuery.setParameter("medicalNumber", medicalNumber);
        nativeQuery.setParameter("id", patient.getId());
        nativeQuery.executeUpdate();
    }

}
